package com.it.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.constant.MessageConstant;
import com.it.constant.StatusConstant;
import com.it.dto.UserLoginDTO;
import com.it.entity.Employee;
import com.it.entity.Users;
import com.it.exception.AccountLockedException;
import com.it.exception.AccountNotFoundException;
import com.it.exception.PasswordErrorException;
import com.it.mapper.UserMapper;
import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @Author: wenjunjay
 * @Date: 2025/02/21/下午6:02
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(UserLoginDTO dto) {
        int count = userMapper.selectByName(dto.getUsername());
        if (count > 0){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_FOUND);
        }
        String MdPwd = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        Users user = Users.builder()
                .username(dto.getUsername())
                .password(MdPwd)
                .nickname(dto.getUsername())
                .build();
        userMapper.insert(user);
    }

    @Override
    public Users login(UserLoginDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();

        //1、根据用户名查询数据库中的数据
        Users user = userMapper.getByName(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //3、返回实体对象
        return user;
    }

}
